<?php
namespace app\common\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\console\input\Option;
use think\helper\Time;

/**
 * 同步企业微信通讯录
 * @author King
 *
 */
class CronSyncWeworkUser extends Command
{

	protected $logName = 'cronSyncWeworkUser';
	protected $isPrint = 1;	// 是否打印信息到终端

	protected function configure()
	{
		$this->setName('cronSyncWeworkUser')
		->addOption('print', 'p', Option::VALUE_OPTIONAL, '是否打印信息到终端(1是，0否)', 1)
		->setDescription('同步企业微信通讯录');
	}

	protected function execute(Input $input, Output $output)
	{
		$msg = "开始同步企业微信通讯录...";
		$this->isPrint = $input->getOption('print');
		$this->_consoleLog($msg, 'start');

		try {
			$wework = new \Wework();
			$response = $wework->userList(1, 1);

			if ($response['errcode'] == 0) {
				$list = $response['userlist'];

				foreach ($list as $k => $v) {
					$upData = [
						'userid' => $v['userid'],
						'name' => $v['name'],
						'mobile' => $v['mobile'],
						'gender' => $v['gender'],
						'email' => $v['email'],
						'avatar' => $v['avatar'],
						'status' => $v['status'],
						'enable' => $v['enable'],
						'update_time' => time(),
					];
					$info = db('weworkUser')->where('userid', $v['userid'])->field('id')->find();
					if ($info) {
						db('weworkUser')->where('id', $info['id'])->update($upData);
					} else {
						$upData['create_time'] = time();
						db('weworkUser')->insertGetId($upData);
					}
				}

				$this->_consoleLog("同步企业微信通讯录完成", 'end');

				$output->write(json_encode(['code' => 1, 'msg' => '处理成功', 'data' => []]));
			} else {
				throw new \Exception($response['errmsg']);
			}

		} catch (\Exception $e) {
			$msg = "错误:".$e->getMessage();
			$this->_consoleLog($msg, 'Exception');
		}
	}

	/**
	 * 记录日志并打印
	 *
	 * @author KING
	 * @date 2020年6月11日
	 *
	 * @param string $msg
	 * @param string $flag
	 * @param string $format
	 */
	private function _consoleLog($msg, $flag, $format=true) {
		if ($this->isPrint) consoleLog($msg, $flag, $format);
		addLog($msg, $this->logName);
	}
}